<template>
	<view class="container">
		<!-- 顶部操作栏 -->
		<view class="header">
			<view class="top-bar">
				<view class="search-box">
					<view class="search-bar">
						<uni-icons type="search" size="16" color="#666666"></uni-icons>
						<input 
							type="text"
							v-model="searchKey"
							placeholder="搜索商品名称"
							class="search-input"
							@input="onSearch"
						/>
						<uni-icons 
							v-if="searchKey"
							type="clear" 
							size="16" 
							color="#999999"
							@click="clearSearch"
						></uni-icons>
					</view>
				</view>
				<button class="add-btn" @click="goAdd">
					<uni-icons type="plus" size="18" color="#fff"></uni-icons>
					<text>发布</text>
				</button>
			</view>
		</view>
		
		<!-- 商品列表 -->
		<scroll-view 
			scroll-y 
			class="goods-list"
			@scrolltolower="loadMore"
			:refresher-enabled="true"
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="goods-item" v-for="item in filteredGoodsList" :key="item.id">
				<image 
					class="goods-img" 
					:src="getGoodsImage(item)" 
					mode="aspectFill"
				></image>
				
				<view class="goods-info">
					<view class="title">{{item.title}}</view>
					<view class="price">￥{{item.price}}</view>
					<view class="stock">库存：{{item.stock}}件</view>
				</view>
				
				<view class="operations">
					<view class="btn-group">
						<button class="edit-btn" @click="editGoods(item)">编辑</button>
						<button class="delete-btn" @click="deleteGoods(item)">删除</button>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty" v-if="filteredGoodsList.length === 0">
				<image src="/static/images/empty-goods.png" mode="aspectFit"></image>
				<text>{{searchKey ? '未找到相关商品' : '暂无商品'}}</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { config } from '@/utils/config.js'

// 商品列表数据
const goodsList = ref([])
// 搜索关键词
const searchKey = ref('')
// 下拉刷新状态
const refreshing = ref(false)
// 分页参数
const page = ref(1)
const pageSize = 10
const hasMore = ref(true)

// 过滤后的商品列表
const filteredGoodsList = computed(() => {
	if (!searchKey.value) return goodsList.value
	
	const key = searchKey.value.toLowerCase()
	return goodsList.value.filter(item => 
		item.title.toLowerCase().includes(key) || 
		item.desc.toLowerCase().includes(key)
	)
})

// 搜索处理
const onSearch = () => {
	// 实时搜索，无需额外处理，computed 会自动更新
}

// 清除搜索
const clearSearch = () => {
	searchKey.value = ''
}

// 获取商品列表
const getGoodsList = async (isRefresh = false) => {
	try {
		if (isRefresh) {
			page.value = 1
			hasMore.value = true
		}
		
		if (!hasMore.value) return
		
		const res = await uni.request({
			url: config.baseUrl + '/api/goods/list',
			method: 'GET',
			data: {
				page: page.value,
				pageSize
			},
			header: {
				'Authorization': uni.getStorageSync('token')
			}
		})
		
		if (res.data.code === 200) {
			const newList = res.data.data
			if (isRefresh) {
				goodsList.value = newList
			} else {
				goodsList.value = [...goodsList.value, ...newList]
			}
			
			hasMore.value = newList.length === pageSize
			page.value++
		} else {
			throw new Error(res.data.message)
		}
	} catch (error) {
		uni.showToast({
			title: '获取商品列表失败',
				icon: 'none'
		})
	}
}

// 下拉刷新
const onRefresh = async () => {
	refreshing.value = true
	await getGoodsList(true)
	refreshing.value = false
}

// 加载更多
const loadMore = () => {
	if (hasMore.value) {
		getGoodsList()
	}
}

// 获取商品图片
const getGoodsImage = (item) => {
	if (item.cover_image) {
		return config.baseUrl + item.cover_image
	}
	if (item.imageUrls && item.imageUrls.length > 0) {
		return item.imageUrls[0]
	}
	return '/static/images/default-goods.png'
}

// 跳转到发布商品页
const goAdd = () => {
	uni.navigateTo({
		url: '/pages/goods/add'
	})
}

// 编辑商品
const editGoods = (item) => {
	// 将完整的商品数据传递给编辑页面
	const query = encodeURIComponent(JSON.stringify({
		id: item.id,
		title: item.title,
		desc: item.desc,
		price: item.price,
		stock: item.stock,
		giftRules: item.giftRules || [],
		imageUrls: item.imageUrls || [],
		cover_image: item.cover_image
	}))
	
	uni.navigateTo({
		url: `/pages/goods/add?goods=${query}`
	})
}

// 删除商品
const deleteGoods = (item) => {
	uni.showModal({
		title: '提示',
		content: '确定要删除该商品吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					const result = await uni.request({
						url: config.baseUrl + `/api/goods/${item.id}`,
						method: 'DELETE',
						data: {
							soft: false
						},
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					})
					
					if (result.data.code === 200) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
							// 重新获取列表
							getGoodsList(true)
					} else {
						throw new Error(result.data.message)
					}
				} catch (error) {
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

onMounted(() => {
	getGoodsList(true)
})

onShow(() => {
	getGoodsList(true)
})
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #f7f8fa;
	padding-bottom: env(safe-area-inset-bottom);
}

.header {
	background: #fff;
	position: sticky;
	top: 0;
	z-index: 100;
	padding: 20rpx 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	
	.top-bar {
		display: flex;
		align-items: center;
		gap: 20rpx;
		
		.search-box {
			flex: 1;
			
			.search-bar {
				height: 72rpx;
				background: #f7f8fa;
				border-radius: 36rpx;
				display: flex;
				align-items: center;
				padding: 0 30rpx;
				
				.search-input {
					flex: 1;
					height: 100%;
					font-size: 28rpx;
					margin: 0 20rpx;
				}
				
				.uni-icons {
					flex-shrink: 0;
				}
			}
		}
		
		.add-btn {
			height: 72rpx;
			min-width: 140rpx;
			background: #ff6b81;
			border-radius: 36rpx;
			padding: 0 30rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			flex-shrink: 0;
			
			text {
				color: #fff;
				font-size: 28rpx;
				margin-left: 8rpx;
			}
		}
	}
}

.goods-list {
	padding: 20rpx;
	
	.goods-item {
		background: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		
		.goods-img {
			width: 160rpx;
			height: 160rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
		}
		
		.goods-info {
			flex: 1;
			
			.title {
				font-size: 28rpx;
				color: #333;
				font-weight: bold;
				margin-bottom: 10rpx;
			}
			
			.price {
				font-size: 32rpx;
				color: #ff6b81;
				font-weight: bold;
				margin-bottom: 10rpx;
			}
			
			.stock {
				font-size: 24rpx;
				color: #666;
				margin-bottom: 10rpx;
			}
		}
		
		.operations {
			.btn-group {
				display: flex;
				gap: 10rpx;
				
				button {
					width: 120rpx;
					height: 52rpx;
					line-height: 52rpx;
					font-size: 24rpx;
					margin: 0;
					padding: 0;
					
					&.edit-btn {
						background: #2196f3;
						color: #fff;
					}
					
					&.delete-btn {
						background: #f44336;
						color: #fff;
					}
				}
			}
		}
	}
}

.empty {
	padding-top: 200rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	
	image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	
	text {
		font-size: 28rpx;
		color: #999;
	}
}
</style> 